﻿namespace YnabCsvConverter.Core.Converters
{
   using System.Collections.Generic;
   using System.Globalization;
   using System.Linq;

   /// <summary>
   /// ING DiBa Converter
   /// </summary>
   [ConverterName("ING DiBa")]
   public class IngDiBaConverter : BaseConverter, IConverter
   {
      /// <summary>
      /// Initializes a new instance of the <see cref="IngDiBaConverter" /> class.
      /// </summary>
      public IngDiBaConverter()
      {
         // The source cvs uses a 'german' culture formatted file.
         SourceCulture = CultureInfo.GetCultureInfo("de");
      }

      /// <summary>
      /// Converts this instance.
      /// </summary>
      /// <param name="sourceFilename">The source filename.</param>
      /// <param name="targetFilename">The target filename.</param>
      /// <param name="mode">The creation mode.</param>
      /// <returns>
      /// The Converter Result.
      /// </returns>
      public ConverterResult Convert(string sourceFilename, string targetFilename, CreationMode mode)
      {
         // Read specific records from source file.
         IEnumerable<IngDiBaRecord> records = ReadRecords<IngDiBaRecord>(sourceFilename, ';', true);

         // Convert records from source file to YNAB records.
         IEnumerable<YnabRecord> ynabRecords = ConvertRecords(records);

         // Write YNAB records to target file.
         WriteRecords(ynabRecords, targetFilename, mode);

         // Return a result
         return new ConverterResult {IsSuccess = true};
      }

      /// <summary>
      /// Converts to ynab lines.
      /// </summary>
      /// <param name="records">The records.</param>
      /// <returns></returns>
      /// <exception cref="System.NotImplementedException"></exception>
      public IEnumerable<YnabRecord> ConvertRecords(IEnumerable<IngDiBaRecord> records)
      {
         return records.Select(ConvertRecord).ToList();
      }

      /// <summary>
      /// Converts to ynab CSV line.
      /// </summary>
      /// <param name="record">The CSV line.</param>
      /// <returns></returns>
      /// <exception cref="System.NotImplementedException"></exception>
      public YnabRecord ConvertRecord(IngDiBaRecord record)
      {
         var ynabRecord = new YnabRecord();

         ynabRecord.SetDate(record.DateTime, SourceCulture);

         var inflow = decimal.Parse(record.Inflow, SourceCulture.NumberFormat);
         var outflow = decimal.Parse(record.Outflow, SourceCulture.NumberFormat);
         var amount = inflow - outflow;

         ynabRecord.SetInflowOutflow(amount);
         ynabRecord.Payee = record.Text;
         ynabRecord.Category = string.Empty;
         ynabRecord.Memo = string.Empty;
         
         return ynabRecord;
      }
   }
}
